package com.eeepay.eeepay_v2.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.activity.LoginActivity;
import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.v2_library.dialog.CustomDialog;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.util.ABConfig;
import com.eeepay.v2_library.util.ABFileUtil;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AppUpdateUtil {

	static File cacheFile;

	static {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			cacheFile = new File(ABFileUtil.SD_CARD_PATH + File.separator + ABConfig.FILE_CACHE_PATH + File.separator + "eeepay.apk");

		} else {
			cacheFile = new File(StorageUtils.getCacheDirectory(MyApplication.getInstance()).getPath(), "eeepay.apk");
		}
	}

	public static String downFlag = "";
	public static String downloadUrl = "";
	public static String verDesc = "";

	/**
	 * 有更新
	 * 
	 * @param mContext
	 * postion 1选择更新，2强制更新（一个按钮）
	 */
	public static void doNewVersionUpdate(final Context mContext) {
		LogUtils.d("doNewVersionUpdate");
		CustomDialog dialog = new CustomDialog(mContext);
		dialog.setTitles("版本更新").setMessage(verDesc);
		dialog.setPositiveButton("马上更新", new OnClickListener() {
			@Override
			public void onClick(View v) {
				downFile(mContext); // 开始下载
			}
		});
		if("2".equals(downFlag)){
			dialog.setCancelable(false);
		}else if("1".equals(downFlag)){
		    dialog.setNegativeButton("稍后再说", null);
		}
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	static boolean down = false;

	private static void downFile(final Context mContext) {
		down = true;
		View view = View.inflate(mContext, R.layout.app_update, null);
		final ProgressBar progress = (ProgressBar) view.findViewById(R.id.progress);
		final TextView tv_progress = (TextView) view.findViewById(R.id.tv_progress);
		final CustomDialog dialog = new CustomDialog(mContext);
		dialog.setTitles("发现新版本").setMessage(verDesc).setView(view);
		if("2".equals(downFlag)){
			dialog.setCancelable(false);
		}else if("1".equals(downFlag)){
		    dialog.setNegativeButton(mContext.getResources().getString(R.string.cancel), new OnClickListener() {
				@Override
				public void onClick(View v) {
					down = false;
				}
			});
		}
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();

		final  Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				switch (msg.what) {
				case 0:
					int pro = (Integer) msg.obj;
					Log.d("Test","pro=="+pro);
					progress.setProgress(pro);
					tv_progress.setText(pro + "%");
					break;
				case 1:
					dialog.dismiss();
					Intent intent = new Intent(Intent.ACTION_VIEW);
					// add by zhuangzeqin 2017年11月29日09:44:33 android 7.0 因为Uri.fromFile引起的FileUriExposedException异常
					// 判断版本大于等于7.0
					Uri data;
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
						data = FileProvider.getUriForFile(mContext,mContext.getPackageName()+".FileProvider",cacheFile);
						// 给目标应用一个临时授权
						intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					}
					else
					{
						data = Uri.fromFile(cacheFile);
					}
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setDataAndType(data, "application/vnd.android.package-archive");
					mContext.startActivity(intent);
					if((mContext instanceof LoginActivity)&&"2".equals(downFlag)){//强制更新，跳转去安装的时候，把登录界面结束
						((Activity)mContext).finish();
					}
					break;
				case 2:
					dialog.dismiss();
					ABFileUtil.deleteFile(cacheFile);
					break;
				}

			}
		};

		new Thread() {
			public void run() {
				try {
					Response response = OkHttpClientManager.getAsyn(downloadUrl, downloadUrl);
					long length = response.body().contentLength();
					InputStream is = response.body().byteStream();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						if (cacheFile.exists()) {
							cacheFile.delete();
						}
						if (!cacheFile.getParentFile().exists())
						{
							cacheFile.getParentFile().mkdirs();//add by zhuangzeqin 2017年11月2日18:16:07 创建目录； 在创建文件
						}
						cacheFile.createNewFile();
						fileOutputStream = new FileOutputStream(cacheFile);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1 && down) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
//								int progress = (int) (count * 100 / length);
								//add by zhuangzeqin 2017年4月19日14:22:19 解决下载过程中出现负数的百分比
								int progress = (int) ((float) count / length * 100);
								Message message = handler.obtainMessage();
								message.what = 0;
								message.obj = progress;
								handler.sendMessage(message);
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					if (down) {
						handler.sendEmptyMessage(1);
					} else {
						handler.sendEmptyMessage(2);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}
